//
//  SearchViewController.m
//  CapriceMusic
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchClickViewController.h"
#import "SearchModel.h"
@interface SearchViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>


/**
 *  点击搜索，覆盖的View
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *  热门搜索数组
 */
@property (nonatomic, strong) NSMutableArray *searchHotArray;
/**
 *  模糊搜索数组
 */
@property (nonatomic, strong) NSMutableArray *searchDimArray;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backDidPress:)];

    self.searchDimArray = [NSMutableArray arrayWithCapacity:0];
    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    navLabel.text = @"搜索";
    navLabel.textColor = [UIColor whiteColor];
    navLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = navLabel;
    
    UILabel *hotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 64, 200, 20)];
    hotLabel.font = [UIFont systemFontOfSize:12];
    hotLabel.textColor = [UIColor colorWithRed:0.2031 green:0.2031 blue:0.2031 alpha:1.0];
    hotLabel.text = @"热门搜索:";
    [self.view addSubview:hotLabel];
    
    [self setUpSearchBar];
    [self getData];
    // Do any additional setup after loading the view.
}

- (void)backDidPress:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.frame = CGRectMake(0, self.view.height + 100, self.view.width, 0);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.frame = CGRectMake(0, self.view.height + 20, self.view.width, 44);
}

#pragma mark - 热门tag网络请求
- (void)getData {
    [JEHNetWorkTool getWithUrl:KSearchHot parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        self.searchHotArray = [NSMutableArray arrayWithArray:result];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.searchHotArray replaceObjectAtIndex:1 withObject:@"梁静茹"];
            [self setUpHotButton];
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - 搜索结果网络请求
- (void)getData:(NSString *)string {
    [self.searchDimArray removeAllObjects];
    [JEHNetWorkTool getWithUrl:KSearchMoHu parameter:@{@"type":@"search_type_mv", @"keyword":string} httpHeader:@{@"App-Id":@"10201029",@"Device-Id":@"5fc617ae1220d0969b23eaab4c8f02b5",@"Device-V":@"QW5kcm9pZF80LjQuNF8xMDgwKjE5MjBfMTEwMDA5MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result) {
            SearchModel *searchModel = [[SearchModel alloc] initWithDictionary:dic];
            [self.searchDimArray addObject:searchModel];
        }
        if (string.length == 0) {
            [self.searchDimArray removeAllObjects];
            [self.tableView reloadData];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - 热门搜索Button
- (void)setUpHotButton {
    
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    for (int i = 0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.backgroundColor = [UIColor colorWithRed:227 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1.0];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.cornerRadius = 10.0;
        [button setTitle:self.searchHotArray[4 * i] forState:UIControlStateNormal];
        CGRect rect = [button.titleLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        [button addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
        button2.backgroundColor = [UIColor colorWithRed:227 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1.0];
        button2.titleLabel.font = [UIFont systemFontOfSize:12];
        [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button2.layer setCornerRadius:10.0];
        
        [button2 setTitle:self.searchHotArray[1 + (4 * i)] forState:UIControlStateNormal];
        NSDictionary *dic2 = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        //    通过字典计算高度和宽度
        CGRect rect2 = [button2.titleLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic2 context:nil];
        
        [button2 addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:button2];
        
        UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];
        button3.backgroundColor = [UIColor colorWithRed:227 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1.0];
        button3.titleLabel.font = [UIFont systemFontOfSize:12];
        [button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button3.layer setCornerRadius:10.0];
        [button3 setTitle:self.searchHotArray[2 + 4 * i] forState:UIControlStateNormal];
        NSDictionary *dic3 = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        //    通过字典计算高度和宽度
        CGRect rect3 = [button3.titleLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic3 context:nil];
        [button3 addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:button3];
        
        UIButton *button4 = [UIButton buttonWithType:UIButtonTypeSystem];
        button4.backgroundColor = [UIColor colorWithRed:227 / 255.0 green:225 / 255.0 blue:225 / 255.0 alpha:1.0];
        button4.titleLabel.font = [UIFont systemFontOfSize:12];
        [button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button4.layer setCornerRadius:10.0];
        [button4 setTitle:self.searchHotArray[3 + 4 * i] forState:UIControlStateNormal];
        NSDictionary *dic4 = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        //    通过字典计算高度和宽度
        CGRect rect4 = [button4.titleLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic4 context:nil];
        [button4 addTarget:self action:@selector(buttonDidPress:) forControlEvents:UIControlEventTouchDown];
        [self.view addSubview:button4];
        
        
        
        //按键总宽
        CGFloat kSumWidth = rect.size.width + rect2.size.width + rect3.size.width + rect4.size.width + 80;
        //屏幕宽度减去按键总宽
        CGFloat kSubWidth = self.view.width - kSumWidth;
        //间距
        CGFloat kSurWidth = kSubWidth / 5;
        button.frame = CGRectMake(kSurWidth, 100 + i * 40, rect.size.width + 20, 20);
        button2.frame = CGRectMake(button.right + kSurWidth, 100 + i * 40, rect2.size.width + 20, 20);
        button3.frame = CGRectMake(button2.right + kSurWidth, 100 + i * 40, rect3.size.width + 20, 20);
        button4.frame = CGRectMake(button3.right + kSurWidth, 100 + i * 40, rect4.size.width + 20, 20);
    }
}

- (void)buttonDidPress:(UIButton *)sender {
    SearchClickViewController *searchClickVc = [[SearchClickViewController alloc] init];
    searchClickVc.searchResult = sender.titleLabel.text;
    [self.navigationController pushViewController:searchClickVc animated:YES];
}

#pragma mark - searchBar
- (void)setUpSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)];
    self.searchBar.delegate = self;
    self.searchBar.barTintColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.placeholder = @"输入艺人、MV或悦单名称";
    self.searchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:self.searchBar];
}

//点击搜索框响应
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    self.navigationController.navigationBarHidden = YES;
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 124)];
    self.myView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.myView];
    
    self.searchBar.frame = CGRectMake(0, 20, self.view.width, 44);
    [self.myView addSubview:self.searchBar];
    
    //segmented
    NSArray *array = @[@"MV", @"悦单", @"艺人"];
    UISegmentedControl *segmented = [[UISegmentedControl alloc] initWithItems:array];
    segmented.frame = CGRectMake(20, self.searchBar.bottom + 20, self.view.width - 40, 30);
    segmented.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    //当前选择的segmented
    segmented.selectedSegmentIndex = 0;
    [self.myView addSubview:segmented];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.myView.bottom, self.view.width, self.view.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
    
    self.searchBar.showsCancelButton = YES;
    for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    return YES;
}
//取消按键
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.navigationController.navigationBarHidden = NO;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.frame = CGRectMake(0, 0, self.view.width, 44);
    self.myView.hidden = YES;
    self.tableView.hidden = YES;
    [self.view addSubview:self.searchBar];
    [self.searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self getData:searchBar.text];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    SearchClickViewController *searchClickVc = [[SearchClickViewController alloc] init];
    searchClickVc.searchResult = searchBar.text;
    [self.navigationController pushViewController:searchClickVc animated:YES];
}

#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDimArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    if (self.searchDimArray.count > indexPath.row) {
        SearchModel *searchModel = self.searchDimArray[indexPath.row];
        cell.textLabel.text = searchModel.word;
    }
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchModel *searchModel = self.searchDimArray[indexPath.row];
    SearchClickViewController *searchClickVc = [[SearchClickViewController alloc] init];
    searchClickVc.searchResult = searchModel.word;
    [self.navigationController pushViewController:searchClickVc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
